<script setup lang="ts">
  import { nextTick, onMounted, ref, unref } from 'vue';
  import {
    activateDeviceApi,
    getDeviceBySnApi,
    removeDeviceApi,
    updateDeviceProductIdApi,
  } from '@/api/hc/device';
  import TestComponent from '@/views/zhm/device/TestComponent';
  import {
    delImageValueApi,
    initDeviceImageApi,
    listDeviceImageApi,
    setImageValueApi,
  } from '@/api/hc/deviceImage';
  import { Persistent } from '@/utils/cache/persistent';
  import { DescItem, Description } from '@/components/Description';
  import { Card, Divider } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { listDeviceUserLinkApi } from '@/api/hc/deviceUserLink';
  import { SN_KEY } from '@/enums/cacheEnum';
  import {
    cfgLogApi,
    powerControlApi,
    sendImageValueApi,
    setPreActiveStatusApi,
  } from '@/api/hc/deviceControl';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Product } from '@/api/hc/iotProduct';
  import { useScript } from '@/hooks/web/useScript';
  import dayjs from 'dayjs';
  import { listDeviceWarnCfgBySnApi } from '@/api/hc/deviceWarnCfg';
  import { userProductAll } from '@/views/hooks/hc/Data';

  let a = ref<string>('123');
  let deviceInfo = ref<any>({});
  let deviceImageList = ref<[]>([]);

  let sn = ref<string>(Persistent.getLocal(SN_KEY) || '');

  const { createMessage } = useMessage();

  onMounted(() => {
    submit();
  });

  const productId = ref<string>('');
  const productList = ref<Product[]>([]);

  function productIdChange(item: Product) {
    console.log(item);
  }

  function updateProductId() {
    updateDeviceProductIdApi({
      sn: sn.value,
      productId: productId.value,
    }).then((res) => {
      createMessage.info('updateProductId ' + res);
    });
  }

  async function getDeviceInfo() {
    deviceInfo.value = await getDeviceBySnApi(sn.value);
    productId.value = deviceInfo.value.productId;
    const point = new BMap.Point(
      parseFloat(deviceInfo.value.lng),
      parseFloat(deviceInfo.value.lat),
    );
    const marker = new BMap.Marker(point); // 创建标注
    map.addOverlay(marker);
    map.centerAndZoom(point, 5);
  }

  async function getDeviceImage() {
    listDeviceImageApi(sn.value).then((res) => {
      deviceImageList.value = res;
    });
  }

  async function submit() {
    console.log(sn.value);
    await initMap();
    productList.value = await userProductAll();
    await getDeviceInfo();
    await getDeviceImage();
    await listDeviceUserLink();
    await listDeviceWarnCfgBySn();
  }

  function snChange() {
    Persistent.setLocal(SN_KEY, sn.value);
  }

  function cfgLog() {
    cfgLogApi({
      sn: sn.value, //sn
      reqType: 'mqttRLog', //"lanLog"  局域网udp日志(wifi模块生效)， "mqttRLog"  远程日志
      expire: 10, //生效时长，单位秒
      level: 3, //日志等级
      port: '', //udp端口
    }).then((res) => {
      createMessage.info('cfgLogApi ' + res);
    });
  }

  const modelKey = ref<string>('');
  const modelVal = ref<string>('');

  function setImageValue() {
    setImageValueApi({
      sn: sn.value,
      key: modelKey.value,
      value: modelVal.value,
    }).then((res) => {
      createMessage.info('setImageValueApi ' + res);
    });
  }

  function delImageValue() {
    delImageValueApi({
      sn: sn.value,
      key: modelKey.value,
    }).then((res) => {
      createMessage.info('delImageValue ' + res);
    });
  }

  function removeDevice() {
    removeDeviceApi({
      sn: sn.value,
    }).then((res) => {
      createMessage.info('removeDevice ' + res);
    });
  }

  const preActiveStatus = ref<number>();
  const preActiveEnv = ref<string>('');
  const preActiveRegion = ref<string>('');

  function setPreActiveStatus() {
    setPreActiveStatusApi({
      sn: sn.value,
      status: preActiveStatus.value,
      env: preActiveEnv.value,
      region: preActiveRegion.value,
    }).then((res) => {
      createMessage.info('removeDevice ' + res);
    });
  }

  const powerModel = ref<number>(0);

  function powerControl() {
    powerControlApi({
      sn: sn.value,
      model: powerModel.value,
    }).then((res) => {
      createMessage.info('removeDevice ' + res);
    });
  }

  const deviceSchema: DescItem[] = [
    {
      field: 'id',
      label: '设备id',
    },
    {
      field: 'deviceName',
      label: '设备名称',
    },
    {
      field: 'productKey',
      label: '产品key',
    },
    {
      field: 'productName',
      label: '产品名称',
    },
    {
      field: 'typeName',
      label: '类型名称',
    },
    {
      field: 'isActivated',
      label: '激活状态',
    },
    {
      field: 'protocolKey',
      label: '协议key',
    },
    {
      field: 'serviceName',
      label: '服务名称',
    },
    {
      label: '状态',
      field: 'deviceStatus',
    },
  ];

  async function listDeviceUserLink() {
    listDeviceUserLinkApi(deviceInfo.value.id).then((res) => {
      deviceUserLinkList.value = res;
    });
  }

  let deviceUserLinkList = ref<[]>([]);
  const deviceUserLinkColumns = [
    {
      title: 'Name',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '级别',
      dataIndex: 'userLevel',
      key: 'userLevel',
    },
  ];

  async function listDeviceWarnCfgBySn() {
    listDeviceWarnCfgBySnApi(sn.value).then((res) => {
      deviceWarnCfgList.value = res;
      res.forEach((item) => {
        if (item.calcKey == 'NOT_IN_LAT_LNG') {
          const pList = [];
          const locs = item.calcValue.split(',');
          for (let i = 0; i < locs.length; i++) {
            const latLng2 = locs[i].split(' ');
            if (latLng2.length === 2) {
              pList.push({
                lat: parseFloat(latLng2[0]),
                lng: parseFloat(latLng2[1]),
              });
            }
          }
          console.log(pList);
          const polyline = new BMap.Polygon(pList, {
            strokeColor: 'blue',
            strokeWeight: 2,
            strokeOpacity: 0.5,
          });
          map.addOverlay(polyline);
        }
      });
    });
  }

  let deviceWarnCfgList = ref<[]>([]);
  const deviceWarnCfgColumns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'targetType',
      dataIndex: 'targetType',
      key: 'targetType',
    },
    {
      title: 'targetId',
      dataIndex: 'targetId',
      key: 'targetId',
    },
    {
      title: 'warnCode',
      dataIndex: 'warnCode',
      key: 'warnCode',
    },
    {
      title: 'paramKey',
      dataIndex: 'paramKey',
      key: 'paramKey',
    },
    {
      title: 'calcKey',
      dataIndex: 'calcKey',
      key: 'calcKey',
    },
    {
      title: 'calcValue',
      dataIndex: 'calcValue',
      key: 'calcValue',
    },
    {
      title: 'msg',
      dataIndex: 'msg',
      key: 'msg',
    },
  ];

  const deviceImageColumns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'paramType',
      key: 'paramType',
    },
    {
      title: '值',
      dataIndex: 'val',
      key: 'val',
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
    },
    {
      title: 'code',
      dataIndex: 'paramCode',
      key: 'paramCode',
    },
    {
      title: 'key',
      dataIndex: 'paramKey',
      key: 'paramKey',
    },
    {
      title: 'func',
      dataIndex: 'func',
      key: 'func',
    },
    {
      title: '时间',
      dataIndex: 'ts',
      key: 'ts',
    },
  ];

  const wrapRef = ref<HTMLDivElement | null>(null);
  const { toPromise: toPromise1 } = useScript({
    src: 'https://api.map.baidu.com/getscript?v=3.0&ak=rU8qkC216C0zEXnKTeKYHzubOHFzowRL&services=&t=20210201100830&s=1',
  });
  const { toPromise: toPromise2 } = useScript({
    src: 'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
  });
  const { toPromise: toPromise3 } = useScript({
    src: 'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
  });

  let map;
  let BMap;

  async function initMap() {
    await toPromise1();
    await toPromise2();
    await toPromise3();
    await nextTick();
    const wrapEl = unref(wrapRef);
    if (!wrapEl) return;
    BMap = (window as any).BMap;
    map = new BMap.Map(wrapEl);
    const point = new BMap.Point(114.0545429, 22.5445741);
    map.centerAndZoom(point, 9);
    map.enableScrollWheelZoom(true);
    // const marker = new BMap.Marker(point); // 创建标注
    // map.addOverlay(marker);
    map.addEventListener('click', function (e) {
      console.log(e.point);
      const point = new BMap.Point(e.point.lng, e.point.lat);
      const marker = new BMap.Marker(point); // 创建标注
      map.addOverlay(marker);
    });
  }

  function sendImageValue(key: string, val: object) {
    const data = {
      sn: sn.value,
      paramMap: {},
      // ttl: 20 * 60 * 1000,
    };
    data.paramMap[key] = val;
    sendImageValueApi(data).then((res) => {
      createMessage.info('sendImageValue ' + JSON.stringify(res));
      getDeviceImage();
    });
  }

  function activateDevice() {
    activateDeviceApi({
      deviceId: deviceInfo.value.id,
    }).then((res) => {
      createMessage.info('activateDevice ' + res);
    });
  }

  function initDeviceImage() {
    initDeviceImageApi(sn.value).then((res) => {
      createMessage.info('activateDevice ' + res);
    });
  }
</script>

<template>
  <PageWrapper class="virtual-scroll-demo">
    <a-space>
      <a-input v-model:value="sn" @change="snChange" />
      <a-button type="primary" @click="submit">获取</a-button>
    </a-space>

    <Description
      size="middle"
      title="设备基础信息"
      :bordered="false"
      :column="3"
      :data="deviceInfo"
      :schema="deviceSchema"
    />
    <Divider />
    <PageWrapper title="设备镜像" contentBackground>
      <a-table :dataSource="deviceImageList" :columns="deviceImageColumns">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'val'">
            <a-space>
              <a-switch
                :disabled="!record.canSet"
                v-if="record.paramType === 'bool'"
                v-model:checked="record.val"
                :checked-value="1"
                :un-checked-value="0"
                @change="sendImageValue(record.paramKey, record.val)"
              />
              <div v-else class="flex">
                <a-input-number
                  :disabled="!record.canSet"
                  v-if="record.paramType === 'int32'"
                  v-model:value="record.val"
                  class="mr"
                />
                <a-input-number
                  :disabled="!record.canSet"
                  v-else-if="record.paramType === 'float'"
                  v-model:value="record.val"
                  class="mr"
                />
                <a-input-number
                  :disabled="!record.canSet"
                  v-else-if="record.paramType === 'double'"
                  v-model:value="record.val"
                  class="mr"
                />
                <a-time-picker
                  :disabled="!record.canSet"
                  v-else-if="record.paramType === 'time'"
                  v-model:value="record.val"
                  value-format="HH:mm:ss"
                  class="mr"
                />
                <a-date-picker
                  :disabled="!record.canSet"
                  v-else-if="record.paramType === 'date'"
                  v-model:value="record.val"
                  class="mr"
                />
                <a-date-picker
                  :disabled="!record.canSet"
                  value-format="x"
                  show-time
                  v-else-if="record.paramType === 'datetime'"
                  v-model:value="record.val"
                  class="mr"
                />
                <a-input :disabled="!record.canSet" v-else v-model:value="record.val" class="mr" />
                <a-button
                  :disabled="!record.canSet"
                  type="primary"
                  @click="sendImageValue(record.paramKey, record.val)"
                  >更新
                </a-button>
              </div>
              <!--              <a-input v-model:value="record.val" :disabled="!record.canSet" />-->
              <!--              <a-button-->
              <!--                type="primary"-->
              <!--                :disabled="!record.canSet"-->
              <!--                @click="sendImageValue(record.paramKey, record.val)"-->
              <!--                >更新-->
              <!--              </a-button>-->
            </a-space>
          </template>
          <template v-else-if="column.key === 'ts'">
            <!--            .tz('GMT+08:00')?-->
            <a>{{ dayjs(record.ts).format('YYYY-MM-DD HH:mm:ss') }}</a>
          </template>
        </template>
      </a-table>
    </PageWrapper>
    <PageWrapper title="报警配置" contentBackground>
      <a-table :dataSource="deviceWarnCfgList" :columns="deviceWarnCfgColumns" />
    </PageWrapper>
    <PageWrapper title="设备分配" contentBackground>
      <a-table :dataSource="deviceUserLinkList" :columns="deviceUserLinkColumns" />
    </PageWrapper>

    <Card title="功能">
      <div class="my-2">
        <h3>日志</h3>
        <div class="py-2">
          <a-button type="primary" @click="cfgLog">开启实时</a-button>
        </div>
      </div>
      <div class="my-2">
        <h3>物模型</h3>
        <div class="py-2">
          <a-space>
            <a-input placeholder="key" v-model:value="modelKey" />
            <a-input placeholder="val" v-model:value="modelVal" />
            <a-button type="primary" @click="setImageValue">设置物模型值</a-button>
            <a-button type="primary" @click="initDeviceImage">修复物模型值</a-button>
            <a-button type="primary" danger @click="delImageValue">删除物模型值</a-button>
          </a-space>
        </div>
      </div>
      <div class="my-2">
        <h3>删除设备</h3>
        <div class="py-2">
          <a-space>
            <a-button type="primary" danger @click="removeDevice">删除设备</a-button>
            <a-button type="primary" @click="activateDevice">激活设备</a-button>
          </a-space>
        </div>
      </div>
      <div class="my-2">
        <h3>设备重激活</h3>
        <div class="py-2">
          <a-space>
            <a-input type="number" v-model:value="preActiveStatus" placeholder="0" />
            <a-input v-model:value="preActiveEnv" placeholder="pre" />
            <a-input v-model:value="preActiveRegion" placeholder="CN" />
            <a-button type="primary" danger @click="setPreActiveStatus">设备重激活</a-button>
          </a-space>
        </div>
      </div>
      <div class="my-2">
        <h3>通讯模块电源设置</h3>
        <div class="py-2">
          <a-space>
            <a-input type="number" v-model:value="powerModel" />
            <a-button type="primary" danger @click="powerControl">通讯模块电源设置</a-button>
          </a-space>
        </div>
      </div>
      <div class="my-2">
        <h3>产品</h3>
        <div class="py-2">
          <a-space>
            <a-select
              v-model:value="productId"
              style="width: 120px"
              class="mr-2"
              @change="productIdChange"
            >
              <template v-for="item in productList" :key="item.id">
                <a-select-option :value="item.id">{{ item.name }}</a-select-option>
              </template>
            </a-select>
            <a-button type="primary" danger @click="updateProductId">更新产品</a-button>
          </a-space>
        </div>
      </div>
    </Card>
    <a-space>
      <a-input disabled v-model:value="deviceInfo.lat" />
      <a-input disabled v-model:value="deviceInfo.lng" />
    </a-space>
    <div ref="wrapRef" :style="{ height: '250px', width: '100%' }"></div>
    <test-component>
      <div>{{ a }}</div>
    </test-component>
  </PageWrapper>
</template>

<style scoped lang="less"></style>
